package com.laowang.project.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.laowang.common.utils.StringUtils;
import com.laowang.project.system.domain.Province;
import com.laowang.project.system.service.AddressService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther laowang
 * @Date 2021/6/24
 * @Description
 */
@Service
public class AddressServiceImpl implements AddressService {

    public static List<Province> provinces = new ArrayList<>();

    @Override
    public List<Province> getProvinces() {

        if(CollectionUtils.isEmpty(provinces)) {
            String data = readFile("/static/json/address.json");

            //System.out.println(data);
            if (StringUtils.isNotBlank(data)) {
                provinces = JSONObject.parseArray(data , Province.class);
            }
        }
        return provinces;
    }


    public static String readFile(String path){
        StringBuffer result = new StringBuffer();
        try {
            org.springframework.core.io.Resource resource = new ClassPathResource(path);
            InputStream inputStream = resource.getInputStream();
            InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
            BufferedReader bufferedReader = new BufferedReader(reader);
            String line = null;
            while((line = bufferedReader.readLine()) != null){
                result.append(line);
            }
            bufferedReader.close();;
            reader.close();
            inputStream.close();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        return result.toString();
    }
}
